<template>
  <div class="step1">
    <Divider />
    <!-- style="padding-top: 20px;" -->
    <div class="step1-form">
      <BasicForm @register="register">
        <template #childList>
          <a-button class="mb-2 ml-2" @click="handleChildAdd">
            <Icon icon="ant-design:plus-circle-outlined" /> {{ '选择客户' }}
          </a-button>
          <a-button class="mb-2 ml-2" @click="handleForm" type="primary">
            <Icon icon="ant-design:plus-circle-outlined" /> {{ '复制客户' }}
          </a-button>
          <a-button class="mb-2 ml-2" @click="handlePrint" type="primary" ghost>
            <Icon icon="ant-design:import-outlined" /> {{ 'Excel导入客户' }}
          </a-button>
          <a-popconfirm
            title="是否确认删除？"
            ok-text="是"
            cancel-text="否"
            placement="bottom"
            @confirm="handleBatchDel()"
          >
            <a-button type="danger" class="mb-2 ml-2">
              <Icon icon="ant-design:delete-outlined" /> {{ '批量删除' }}
            </a-button>
          </a-popconfirm>
          <BasicTable @register="registerChildTable" @row-click="handleChildRowClick"> </BasicTable>
        </template>
      </BasicForm>
      <div style="width: 100%; display: flex; justify-content: center; margin-bottom: 50px">
        <a-button type="primary" @click="customSubmitFunc()">下一步</a-button>
      </div>
    </div>
    <Divider />
    <div class="text-xl">
      <p>说明：</p>
      <p> ①勾选了【是否清除现有价格】会清除当前客户的所有已生效价格。</p>
      <p> ②勾选了【是否覆盖已有价格】会更新存货编码相同的价格，不勾选则跳过。</p>
    </div>

    <ListSelect
      ref="listSelectRef"
      selectType="basPersonSelect"
      :selectList="selectListRef"
      :checkbox="true"
      @select="handSelect"
      v-show="false"
    />
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <FormImport @register="registerImportModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  import { BasicForm, useForm, FormSchema } from '/@/components/Form';
  import { step1Schemas } from './data';
  import { Select, Input, Divider } from 'ant-design-vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { Icon } from '/@/components/Icon';
  import { ListSelect } from '/@/components/ListSelect';
  import { useMessage } from '/@/hooks/web/useMessage';
  import InputForm from './Step1Form.vue';
  import { useDrawer } from '/@/components/Drawer';
  import FormImport from './formImport.vue';
  import { useModal } from '/@/components/Modal';
  

  const emit = defineEmits(['next']);
  const { showMessage } = useMessage();

  const listSelectRef = ref<any>(null);
  const selectListRef = ref<any>([]);

  const inputFormSchemas: FormSchema[] = [
    // {
    //   label: '',
    //   field: 'cusCode',
    //   fieldLabel: 'cusName',
    //   component: 'ListSelect',
    //   componentProps: {
    //     selectType: 'basPersonSelect',
    //     placeholder: '请选择一个客户',
    //   },
    //   required: true,
    // },
    // {
    //   label: '',
    //   field: 'cusCode',
    //   component: 'Input',
    //   componentProps: {
    //     placeholder: '客户编码',
    //   },
    //   dynamicDisabled: true,
    // },
    {
      label: '',
      field: 'childList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'childList',
    },
    {
      field: 'paramClearHisPrice',
      // defaultValue: '1',
      component: 'CheckboxGroup',
      componentProps: {
        // dictType: 'sys_yes_no',
        options: [{ label: '是否清除现有价格', value: '1' }],
      },
    },
    {
      field: 'paramReplaceHisPrice',
      component: 'CheckboxGroup',
      componentProps: {
        // dictType: 'sys_yes_no',
        options: [{ label: '是否覆盖已有价格', value: '1' }],
      },
    },
  ];

  const tableColumns: BasicColumn[] = [
    {
      title: '客户编码',
      dataIndex: 'code',
      width: 100,
      align: 'left',
    },
    {
      title: '客户名称',
      dataIndex: 'name',
      width: 200,
      align: 'left',
    },
    {
      title: '所属分公司',
      dataIndex: 'exDefine12',
      width: 200,
      align: 'left',
    },
  ];

  const [register, { validate, setFieldsValue }] = useForm({
    labelWidth: 180,
    schemas: inputFormSchemas,
    showActionButtonGroup: false,
    // schemas: step1Schemas,
    // actionColOptions: {
    //   span: 14,
    // },
    // showResetButton: false,
    // submitButtonOptions: {
    //   text: '下一步',
    // },
    // submitFunc: customSubmitFunc,
  });

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerChildTable, childTable] = useTable({
    actionColumn: {
      width: 40,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleChildDelete.bind(this, record),
          },
        },
      ],
    },
    indexColumnProps: {
      width: 40,
    },
    columns: tableColumns,
    rowKey: 'code',
    pagination: false,
    bordered: true,
    size: 'small',
    // inset: true,
    canResize: true,
    resizeHeightOffset: 400,
    rowSelection: {
      type: 'checkbox',
    },
  });


  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }
  // async function setChildTableData(_res: Recordable) {
  //   childTable.setColumns([
  //     {
  //       title: '单行文本',
  //       dataIndex: 'testInput',
  //       width: 130,
  //       align: 'left',

  //     },
  //     {
  //       title: '多行文本',
  //       dataIndex: 'testTextarea',
  //       width: 130,
  //       align: 'left',
  //     },
  //     {
  //       title: '下拉框',
  //       dataIndex: 'testSelect',
  //       width: 130,
  //       align: 'left',
  //       dictType: 'sys_menu_type',
  //     },

  //   ]);
  //   childTable.setTableData(record.value.childList || []);
  // }

  function handleChildAdd() {
    selectListRef.value = [];
    listSelectRef.value.openSelectModal();
    // document.getElementById('form_item_selIds')?.click();
    // soReturnApplyRdsTable.insertTableDataRecord({
    //   id: new Date().getTime(),
    //   isNewRecord: true,
    //   editable: true,
    // });
  }

  function handleChildDelete(record: Recordable) {
    childTable.deleteTableDataRecord(record);
  }

  function handleBatchDel() {
    if (childTable.getSelectRows().length) {
      childTable.getSelectRows().forEach((record) => {
        childTable.deleteTableDataRecord(record);
      });
      childTable.clearSelectedRowKeys();
    } else {
      showMessage('请先选择一行数据！！', 'warning');
    }
  }

  function handleChildRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  

  function handleSuccess(selectData) {
    childTable.setTableData(selectData)
  }

  function handSelect(selectData) {
    selectData.forEach((item) => {
      let flag = true;
      childTable.getDataSource().forEach((res) => {
        if (res.code == item.code) {
          flag = false;
        }
      });
      if (flag) {
        childTable.insertTableDataRecord({
          ...item,
          // id: new Date().getTime() + item.id,
          // editable: true,
          // isNewRecord: true,
        });
      }
    });
  }
  onMounted(async () => {
    setFieldsValue({ paramClearHisPrice: '1', paramReplaceHisPrice: '1' });
  });

  async function customSubmitFunc() {
    try {
      console.log(childTable.getDataSource(), '=======');
      let arr = await childTable.getDataSource();
      if (!arr.length) {
        showMessage('请先选择客户！');
        return;
      }
      const values = await validate();
      values.list = arr;
      values.paramClearHisPrice = values.paramClearHisPrice || '';
      values.paramReplaceHisPrice = values.paramReplaceHisPrice || '';
      emit('next', values);
    } catch (error) {
      //
    }
  }

  const [registerImportModal, { openModal: importModal }] = useModal();
  async function handlePrint() {
    importModal(true, {});
  }
</script>
<style lang="less" scoped>
  .step1 {
    &-form {
      width: 80%;
      margin: 0 auto;
    }

    h3 {
      margin: 0 0 12px;
      color: @text-color-base;
      font-size: 16px;
      line-height: 32px;
    }

    h4 {
      margin: 0 0 4px;
      color: @text-color-base;
      font-size: 14px;
      line-height: 22px;
    }

    p {
      color: @text-color-base;
    }
  }

  .pay-select {
    width: 20%;
  }

  .pay-input {
    width: 70%;
  }
</style>
